package com.ponhu.ea2.stockcenter.vo;

import com.ponhu.ea2.stockcenter.enums.ResponseCodeEnum;
import lombok.Data;
import lombok.experimental.Accessors;

import java.beans.Transient;
import java.io.Serializable;

/**
 * 接口返回值包装类
 */
@Data
@Accessors(chain = true)
public class ReturnResponseBean<T> implements Serializable {

    private static final long serialVersionUID = 8393470017411877440L;

    private final static Integer SUCCESS_CODE = 200;

    private final static String SUCCESS_MSG = "success";

    private int code;

    private String msg;

    private T data;

    /**
     * 不带数据的成功结果
     */
    public ReturnResponseBean() {
        this.code = SUCCESS_CODE;
        this.msg = SUCCESS_MSG;
        this.data = null;
    }

    /**
     * 带数据的成功结果
     *
     * @param data
     */
    public ReturnResponseBean(T data) {
        this.code = SUCCESS_CODE;
        this.msg = SUCCESS_MSG;
        this.data = data;
    }

    /**
     * 不带数据的失败结果
     *
     * @param code
     * @param msg
     */
    public ReturnResponseBean(Integer code, String msg) {
        this.code = code;
        this.msg = msg;
        this.data = null;
    }

    /**
     * 不带数据的失败结果
     *
     * @param responseCodeEnum
     */
    public ReturnResponseBean(ResponseCodeEnum responseCodeEnum, T data) {
        this.code = responseCodeEnum.getCode();
        this.msg = responseCodeEnum.getMsg();
        this.data = data;
    }

    /**
     * 带数据的失败结果
     *
     * @param code
     * @param msg
     * @param data
     */
    public ReturnResponseBean(Integer code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public static <T> ReturnResponseBean<T> error() {
        return new ReturnResponseBean<>(ResponseCodeEnum.EXCEPTION_FAIL.getCode(), ResponseCodeEnum.EXCEPTION_FAIL.getMsg(), null);
    }

    public static <T> ReturnResponseBean<T> error(String msg) {
        return new ReturnResponseBean<>(-1, msg, null);
    }

    public static <T> ReturnResponseBean<T> error(Integer code, String msg) {
        return new ReturnResponseBean<>(code, msg, null);
    }

    public static <T> ReturnResponseBean<T> error(ResponseCodeEnum responseCodeEnum) {
        return new ReturnResponseBean<>(responseCodeEnum, null);
    }

    public static <T> ReturnResponseBean<T> error(ResponseCodeEnum responseCodeEnum, T data) {
        return new ReturnResponseBean<>(responseCodeEnum, data);
    }

    public static <T> ReturnResponseBean<T> ok() {
        return new ReturnResponseBean<>(SUCCESS_CODE, SUCCESS_MSG);
    }

    public static <T> ReturnResponseBean<T> ok(T data) {
        return new ReturnResponseBean<>(SUCCESS_CODE, SUCCESS_MSG, data);
    }

    @Transient
    public boolean isOk() {
        return this.getCode() == SUCCESS_CODE;
    }

    @Transient
    public boolean isError() {
        return this.getCode() != SUCCESS_CODE;
    }

}
